
import { ref, watchEffect, watch } from 'vue'

export function useStorage(name, value = []) {
    let old = localStorage.getItem(name) || JSON.stringify(value)
    let data = ref(JSON.parse(old))
    watchEffect(() => {
        localStorage.setItem(name, JSON.stringify(data.value))
    })
    return data
}

export function useFavicon(newIcon) {
    const favicon = ref(newIcon)

    const updateIcon = (icon) => {
        document.head
            .querySelectorAll(`link[rel*="icon"]`)
            .forEach(el => el.href = `${icon}`)
    }
    const reset = () => favicon.value = '/favicon.ico'
    const toggle = () => {
        favicon.value = (favicon.value === '/geek.webp')
            ? '/favicon.ico'
            : '/geek.webp'
    }

    watch(favicon, updateIcon)
    return { favicon, reset, toggle }
}

function random(min = 0, max = 255) {
    return Math.floor(Math.random() * (max - min + 1) + min)
}
export function useColor(val = 'black') {
    let color = ref(val)
    const change = () => color.value = `rgb(${random()}, ${random()}, ${random()})`
    return { color, change }

}